import React, { useState, useRef } from "react";
import { flushSync } from "react-dom";

interface Todo {
  id: number;
  text: string;
}
let nextId = 0;
let initialTodos: Todo[] = [];
for (let i = 0; i < 20; i++) {
  initialTodos.push({
    id: nextId++,
    text: "待办 #" + (i + 1)
  });
}

const TodoList: React.FC = () => {
  const listRef = useRef<HTMLUListElement>(null);
  const [text, setText] = useState("");
  const [todos, setTodos] = useState(initialTodos);

  function handleAdd() {
    const newTodo: Todo = { id: nextId++, text };
    // 强制更新dom
    flushSync(() => {
      setText("");
      setTodos([...todos, newTodo]);
    });
    console.log(listRef.current);
    listRef.current?.lastElementChild?.scrollIntoView({
      behavior: "smooth",
      block: "nearest"
    });
  }

  return (
    <>
      <button onClick={handleAdd}>添加</button>
      <input value={text} onChange={e => setText(e.target.value)} />
      <ul ref={listRef} style={{ height: 300, overflow: "auto" }}>
        {todos.map(todo => (
          <li key={todo.id}>{todo.text}</li>
        ))}
      </ul>
    </>
  );
};
export default TodoList;
